<template>
  <div ref="chart"></div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'chartPie',
  props: {
    value: Array,
    text: String,
    subtext: String
  },
  data () {
    return {
      chart: null
    }
  },
  watch: {
    // 对应props里的value
      value: {
          handler() {
            this.drawPie();
          },
          deep: true
      }
  },
  beforeDestroy() {
        if (!this.chart) {
            return
        }
      this.chart.dispose()
      this.chart = null
  },

  methods: {
    drawPie (){
      this.$nextTick(() => {
          let legend = this.value.map(_ => _.name)
          let option = {
            title: {
              text: this.text,
              subtext: this.subtext,
              x: 'center'
            },
            tooltip: {
              trigger: 'item',
              formatter: '{b} {c}%'
            },
            legend: {
              orient: 'vertical',
              bottom: 'bottom',
              data: legend
            },
            color: ['#32dadd', '#b6a2de'],
            series: [
              {
                type: 'pie',
                radius: '55%',
                center: ['50%', '50%'],
                data: this.value,
                label: {
                    show: true,//饼图上是否出现标注文字 标注各模块代表什么  默认是true
                    position: 'inner',//控制饼图上标注文字相对于饼图的位置  默认位置在饼图外
                },
                labelLine: {
                    show: false//官网demo里外部标注上的小细线的显示隐藏    默认显示
                },
              }
            ]
          }
          this.chart = echarts.init(this.$refs.chart)
          this.chart.setOption(option)
          window.addEventListener("resize", this.handleWindowResize);
        })
    },
    handleWindowResize() {
      if (!this.chart) return;
      this.chart.resize();
    },
  },
  mounted () {
    this.drawPie()
  },
}
</script>
